<template>
  <div class="lost-and-found-container">
	<el-row type="flex" justify="center" class="page-header" style="margin-bottom: 30px;">
	    <el-col :span="24" class="text-center">
	        <div class="title-wrapper">
	        <i class="el-icon-search el-icon--large"></i>
	        <h1 class="main-title">失物招领管理系统</h1>
	        <p class="sub-title">管理失物信息，助力物品找回</p>
	        </div>
	    </el-col>
	</el-row>
    <!-- 详情对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="失物详情"
      width="70%"
      destroy-on-close
    >
      <el-descriptions title="失物信息" direction="vertical" :column="4" border>
        <el-descriptions-item label="ID" :span="2">{{ currentItem.id }}</el-descriptions-item>
        <el-descriptions-item label="失物名称" :span="2">{{ currentItem.itemName }}</el-descriptions-item>
        <el-descriptions-item label="发现时间" :span="2">{{ formatDateTime(currentItem.foundTime) }}</el-descriptions-item>
        <el-descriptions-item label="发现地点" :span="2">{{ currentItem.foundLocation || '无' }}</el-descriptions-item>
        <el-descriptions-item label="发现人" :span="2">{{ currentItem.finderName || '无' }}</el-descriptions-item>
        <el-descriptions-item label="联系方式" :span="2">{{ currentItem.contactInfo || '无' }}</el-descriptions-item>
        <el-descriptions-item label="状态" :span="2">
          <el-tag :type="currentItem.status === 'LOST' ? 'warning' : 'success'">
            {{ currentItem.status === 'LOST' ? '未认领' : '已认领' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="记录创建时间" :span="2">{{ formatDateTime(currentItem.createTime) }}</el-descriptions-item>
        <el-descriptions-item label="备注信息" :span="4">{{ currentItem.remarks || '无' }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>


    <!-- 编辑对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑失物信息"
      width="60%"
      destroy-on-close
    >
      <el-form 
        :model="editForm" 
        :rules="rules" 
        ref="editFormRef" 
        label-width="120px" 
        class="demo-ruleForm"
      >
        <el-form-item label="ID" prop="id" disabled>
          <el-input v-model="editForm.id"></el-input>
        </el-form-item>
        <el-form-item label="失物名称" prop="itemName">
          <el-input v-model="editForm.itemName"></el-input>
        </el-form-item>
        <el-form-item label="发现时间" prop="foundTime">
          <el-date-picker
            v-model="editForm.foundTime"
            type="datetime"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="选择发现时间"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="发现地点" prop="foundLocation">
          <el-input v-model="editForm.foundLocation"></el-input>
        </el-form-item>
        <el-form-item label="发现人" prop="finderName">
          <el-input v-model="editForm.finderName"></el-input>
        </el-form-item>
        <el-form-item label="联系方式" prop="contactInfo">
          <el-input v-model="editForm.contactInfo"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="editForm.status" placeholder="请选择状态">
            <el-option label="未认领" value="LOST"></el-option>
            <el-option label="已认领" value="CLAIMED"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注信息" prop="remarks">
          <el-input v-model="editForm.remarks" type="textarea" rows="3"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitEditForm">确定</el-button>
          <el-button @click="editDialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>


    <!-- 新增对话框 -->
    <el-dialog
      v-model="addDialogVisible"
      title="新增失物信息"
      width="60%"
      destroy-on-close
    >
      <el-form 
        :model="addForm" 
        :rules="rules" 
        ref="addFormRef" 
        label-width="120px"
      >
        <el-form-item label="失物名称" prop="itemName">
          <el-input v-model="addForm.itemName"></el-input>
        </el-form-item>
        <el-form-item label="发现时间" prop="foundTime">
          <el-date-picker
            v-model="addForm.foundTime"
            type="datetime"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="选择发现时间"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="发现地点" prop="foundLocation">
          <el-input v-model="addForm.foundLocation"></el-input>
        </el-form-item>
        <el-form-item label="发现人" prop="finderName">
          <el-input v-model="addForm.finderName"></el-input>
        </el-form-item>
        <el-form-item label="联系方式" prop="contactInfo">
          <el-input v-model="addForm.contactInfo"></el-input>
        </el-form-item>
        <el-form-item label="备注信息" prop="remarks">
          <el-input v-model="addForm.remarks" type="textarea" rows="3"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitAddForm">提交</el-button>
          <el-button @click="addDialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>


    <!-- 数据操作区 -->
    <el-row>
      <el-row :gutter="10" style="width: 100%; margin-bottom: 20px; align-items: center;">
        <el-col :span="6">
          <el-input 
            placeholder="输入名称进行查询" 
            v-model="searchName" 
            style="width: 100%;"
            @keyup.enter="handleSearch"
          ></el-input>
        </el-col>
        <el-col :span="6">
          <el-input 
            placeholder="输入关键词（名称/地点/备注）" 
            v-model="searchKeyword" 
            style="width: 100%;"
            @keyup.enter="handleKeywordSearch"
          ></el-input>
        </el-col>
        <el-col :span="2">
          <el-button 
            type="primary" 
            @click="handleSearch" 
            style="width: 100%;"
          >
            <i class="el-icon-search"></i> 名称搜索
          </el-button>
        </el-col>
        <el-col :span="2">
          <el-button 
            type="primary" 
            @click="handleKeywordSearch" 
            style="width: 100%;"
          >
            <i class="el-icon-search"></i> 关键词搜索
          </el-button>
        </el-col>
        <el-col :span="2">
          <el-button 
            type="success" 
            @click="resetSearch" 
            style="width: 100%;"
          >
            <i class="el-icon-refresh"></i> 重置
          </el-button>
        </el-col>
        <el-col :span="2">
          <el-button 
            type="primary" 
            @click="openAddDialog" 
            style="width: 100%;"
          >
            <i class="el-icon-plus"></i> 新增
          </el-button>
        </el-col>
      </el-row>
      
      <!-- 表格部分 -->
      <el-table 
        :data="filteredData.slice((currentPage-1)*pageSize, currentPage*pageSize)" 
        border 
        style="width: 100%;"
        height="450"
        @sort-change="handleSortChange"
      >
        <el-table-column 
          prop="id" 
          label="ID" 
          width="80" 
          align="center" 
          sortable="custom"
        ></el-table-column>
        <el-table-column prop="itemName" label="失物名称" align="center"></el-table-column>
        <el-table-column 
          prop="foundTime" 
          label="发现时间" 
          width="180" 
          align="center" 
          sortable="custom"
        >
          <template #default="scope">{{ formatDateTime(scope.row.foundTime) }}</template>
        </el-table-column>
        <el-table-column prop="foundLocation" label="发现地点" align="center"></el-table-column>
        <el-table-column 
          prop="status" 
          label="状态" 
          width="100" 
          align="center"
        >
          <template #default="scope">
            <el-tag :type="scope.row.status === 'LOST' ? 'warning' : 'success'">
              {{ scope.row.status === 'LOST' ? '未认领' : '已认领' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column 
          prop="createTime" 
          label="创建时间" 
          width="180" 
          align="center" 
          sortable="custom"
        >
          <template #default="scope">{{ formatDateTime(scope.row.createTime) }}</template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <div class="operation-buttons">
              <el-button type="primary" size="mini" @click="openDetailDialog(scope.row)">
                <i class="el-icon-view"></i> 查看
              </el-button>
              <el-button type="warning" size="mini" @click="openEditDialog(scope.row)">
                <i class="el-icon-edit"></i> 编辑
              </el-button>
              <el-button type="danger" size="mini" @click="deleteItem(scope.row.id)">
                <i class="el-icon-delete"></i> 删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <el-row type="flex" justify="center" style="margin-top: 20px;">
        <el-pagination 
          @size-change="handleSizeChange" 
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5,10,20,50]" 
          :page-size="pageSize" 
          :total="filteredData.length"
          layout="total, sizes, prev, pager, next, jumper"
        ></el-pagination>
      </el-row>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { post } from '../../utils/axios.js'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'


// 对话框状态
const dialogVisible = ref(false)
const editDialogVisible = ref(false)
const addDialogVisible = ref(false)

// 搜索条件
const searchName = ref('')
const searchKeyword = ref('')

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)

// 排序相关
const sortProp = ref('')
const sortOrder = ref('')

// 数据存储
const lostAndFoundList = ref([])
const filteredData = ref([])

// 表单引用
const editFormRef = ref(null)
const addFormRef = ref(null)

// 当前选中的失物信息
const currentItem = reactive({
  id: '',
  itemName: '',
  foundTime: '',
  foundLocation: '',
  remarks: '',
  finderName: '',
  contactInfo: '',
  status: '',
  createTime: ''
})

// 编辑表单数据
const editForm = reactive({
  id: '',
  itemName: '',
  foundTime: '',
  foundLocation: '',
  remarks: '',
  finderName: '',
  contactInfo: '',
  status: ''
})

// 新增表单数据
const addForm = reactive({
  itemName: '',
  foundTime: '',
  foundLocation: '',
  remarks: '',
  finderName: '',
  contactInfo: ''
})

// 表单验证规则
const rules = reactive({
  itemName: [
    { required: true, message: '请输入失物名称', trigger: 'blur' },
    { min: 1, max: 100, message: '名称长度在 1 到 100 个字符', trigger: 'blur' }
  ],
  foundTime: [
    { required: true, message: '请选择发现时间', trigger: 'change' }
  ],
  foundLocation: [
    { required: true, message: '请输入发现地点', trigger: 'blur' },
    { min: 1, max: 200, message: '地点长度在 1 到 200 个字符', trigger: 'blur' }
  ]
})

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '无'
  return new Date(dateTime).toLocaleString()
}

// 处理排序变化
function handleSortChange({ prop, order }) {
  sortProp.value = prop;
  sortOrder.value = order;
  if (prop && order) {
    filteredData.value = [...filteredData.value].sort((a, b) => {
      let valA = a[prop];
      let valB = b[prop];
      // 处理日期类型排序
      if (prop === 'foundTime' || prop === 'createTime') {
        valA = new Date(valA);
        valB = new Date(valB);
      }
      // 升序/降序处理
      if (order === 'ascending') {
        return valA > valB ? 1 : -1;
      } else {
        return valA < valB ? 1 : -1;
      }
    });
  }
}

// 打开详情对话框
function openDetailDialog(row) {
  dialogVisible.value = true
  const loading = ElLoading.service({ text: '加载详情中...' })
  
  // 由于后端没有专门的getById接口，直接使用行数据
  Object.assign(currentItem, row);
  loading.close()
}

// 打开编辑对话框
function openEditDialog(item) {
  editDialogVisible.value = true
  Object.assign(editForm, {
    id: item.id,
    itemName: item.itemName,
    foundTime: item.foundTime,
    foundLocation: item.foundLocation,
    remarks: item.remarks,
    finderName: item.finderName,
    contactInfo: item.contactInfo,
    status: item.status
  })
}

// 打开新增对话框
function openAddDialog() {
  addDialogVisible.value = true
  if (addFormRef.value) {
    addFormRef.value.resetFields()
  }
  // 重置表单
  Object.assign(addForm, {
    itemName: '',
    foundTime: '',
    foundLocation: '',
    remarks: '',
    finderName: '',
    contactInfo: ''
  })
}

// 提交编辑表单
function submitEditForm() {
  editFormRef.value.validate((valid) => {
    if (!valid) return;
    
    const loading = ElLoading.service({ text: '更新中...' })
    post('/sc/lostandfound/update', editForm, (res) => {
      loading.close()
      if (res.status === 1 || res.msg.includes('成功')) {
        ElMessage.success('更新成功！')
        editDialogVisible.value = false
        fetchLostAndFoundList()
      } else {
        ElMessage.error(res.msg || '更新失败')
      }
    })
  })
}

// 提交新增表单
function submitAddForm() {
  addFormRef.value.validate((valid) => {
    if (!valid) return;
    
    const loading = ElLoading.service({ text: '添加中...' })
    post('/sc/lostandfound/add', addForm, (res) => {
      loading.close()
      if (res.status === 1 || res.msg.includes('成功')) {
        ElMessage.success('添加成功！')
        addDialogVisible.value = false
        fetchLostAndFoundList()
      } else {
        ElMessage.error(res.msg || '添加失败')
      }
    })
  })
}

// 删除失物信息
function deleteItem(id) {
  ElMessageBox.confirm(`确定删除ID为 ${id} 的失物信息吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const loading = ElLoading.service({ text: '删除中...' })
    post('/sc/lostandfound/delete', { id }, (res) => {
      loading.close()
      if (res.status === 1 || res.msg.includes('成功')) {
        ElMessage.success('删除成功！')
        fetchLostAndFoundList()
      } else {
        ElMessage.error(res.msg || '删除失败')
      }
    })
  }).catch(() => {})
}

// 按名称搜索
function handleSearch() {
  const loading = ElLoading.service({ text: '搜索中...' })
  
  if (searchName.value) {
    post('/sc/lostandfound/search', { name: searchName.value }, (res) => {
      loading.close()
      if (res.status === 1 && res.data) {
        filteredData.value = res.data
        showSearchResultMessage()
        currentPage.value = 1
      } else {
        ElMessage.error(res.msg || '搜索失败')
        filteredData.value = []
      }
    })
  } else {
    filteredData.value = [...lostAndFoundList.value]
    loading.close()
    showSearchResultMessage()
    currentPage.value = 1
  }
  
  // 应用当前排序
  if (sortProp.value && sortOrder.value) {
    handleSortChange({ prop: sortProp.value, order: sortOrder.value });
  }
}

// 按关键词搜索
function handleKeywordSearch() {
  const loading = ElLoading.service({ text: '搜索中...' })
  
  if (searchKeyword.value) {
    post('/sc/lostandfound/search1', { keyword: searchKeyword.value }, (res) => {
      loading.close()
      if (res.status === 1 && res.data) {
        filteredData.value = res.data
        showSearchResultMessage()
        currentPage.value = 1
      } else {
        ElMessage.error(res.msg || '搜索失败')
        filteredData.value = []
      }
    })
  } else {
    filteredData.value = [...lostAndFoundList.value]
    loading.close()
    showSearchResultMessage()
    currentPage.value = 1
  }
  
  // 应用当前排序
  if (sortProp.value && sortOrder.value) {
    handleSortChange({ prop: sortProp.value, order: sortOrder.value });
  }
}

// 显示搜索结果消息
function showSearchResultMessage() {
  if (filteredData.value.length > 0) {
    ElMessage.success(`找到 ${filteredData.value.length} 条记录`)
  } else {
    ElMessage.warning('未找到匹配记录')
  }
}

// 重置搜索
function resetSearch() {
  searchName.value = ''
  searchKeyword.value = ''
  filteredData.value = [...lostAndFoundList.value]
  currentPage.value = 1
  // 重置排序
  sortProp.value = ''
  sortOrder.value = ''
}

// 分页大小变化
function handleSizeChange(val) {
  pageSize.value = val
  currentPage.value = 1
}

// 当前页变化
function handleCurrentChange(val) {
  currentPage.value = val
}

// 获取所有失物信息
function fetchLostAndFoundList() {
  const loading = ElLoading.service({ text: '加载中...' })
  post('/sc/lostandfound/getAll', {}, (res) => {
    loading.close()
    if (res.status === 1 && res.data) {
      lostAndFoundList.value = res.data
      filteredData.value = [...res.data]
      // 应用排序
      if (sortProp.value && sortOrder.value) {
        handleSortChange({ prop: sortProp.value, order: sortOrder.value });
      }
    } else {
      ElMessage.error(res.msg || '获取数据失败')
      lostAndFoundList.value = []
      filteredData.value = []
    }
  })
}

// 页面加载时获取数据
onMounted(() => {
  fetchLostAndFoundList()
})
</script>

<style scoped>
.lost-and-found-container {
  width: auto;
  padding: 20px;
}

/* 标题样式 */
.page-header {
  padding: 10px 0;
  border-bottom: 1px solid #e5e7eb;
}

.title-wrapper {
  display: inline-flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.main-title {
  font-size: 28px;
  font-weight: 600;
  color: #1f2937;
  margin: 0;
  display: flex;
  align-items: center;
  gap: 12px;
}

.sub-title {
  font-size: 16px;
  color: #6b7280;
  margin: 0;
}

.el-icon--large {
  font-size: 28px;
  color: #409eff;
}

.operation-buttons {
  display: flex;
  gap: 4px;
}

.operation-buttons .el-button--mini {
  padding: 1px 6px;
  font-size: 12px;
  height: 24px;
  min-width: auto;
}

.el-table {
  margin-top: 20px;
}

.el-pagination {
  margin-top: 20px;
}

.el-form-item .el-button,
.el-col .el-button {
  margin-right: 5px;
}

.el-form {
  padding: 10px;
}

.el-descriptions {
  margin-bottom: 20px;
}
</style>